/**
 * Created with IntelliJ IDEA
 * Description：单例模式
 * User：chenshu
 * Date：2023-11-08
 * Time：10:59
 */
//饿汉模式
class Singleton {
    //使用静态成员表示实例
    private static Singleton instance = new Singleton();
    public static Singleton getInstance() {
        return instance;
    }

    //堵住了new其他实例的口子
    private Singleton() {}
}

//懒汉模式
class SingletonLazy {
    //此处没有创建实例
    //加上volatile更稳妥
    volatile private static SingletonLazy instance = null;
    //首次调用getInstance才创建实例
    public static SingletonLazy getInstance() {
        //外层if判定是否已经初始化好，降低锁竞争的概率
        if (instance == null) {
            //初始化之前有读写，线程不安全，加锁
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    private SingletonLazy() {};
}

public class Demo3 {
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance2 == instance);
    }
}
